package cn.chanel.mall.init;

import cn.chanel.mall.repository.CategoryRepository;
import cn.chanel.mall.repository.GoodsRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

@Slf4j
@Component
@Configuration
public class MallApplicationRunner implements ApplicationRunner {

    @Value("classpath:sql/data.sql")
    private org.springframework.core.io.Resource businessScript;

    @Resource
    private CategoryRepository categoryRepository;

    @Resource
    private GoodsRepository goodsRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("data init finish!");
    }

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        // 设置数据源
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator(dataSource));
        return initializer;
    }

    private DatabasePopulator databasePopulator(DataSource dataSource) {
        final ResourceDatabasePopulator popular = new ResourceDatabasePopulator();
        try {
            final DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
            if(metaData.toString().contains("file") &&
                    (goodsRepository.findAll().size() == 0 || categoryRepository.findAll().size() == 0)){
                log.info("File type databases, but data size is zero! -> Run SQL Scripts !!!");
                popular.addScripts(businessScript);
            }else if(metaData.toString().contains("mem")){
                log.info("Mem type databases -> Run SQL Scripts !!!");
                popular.addScripts(businessScript);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return popular;
    }
}
